import os
import tempfile
import subprocess
import logging
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse

app = FastAPI()

# 添加 CORS 中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*"],  # 允许所有头
)

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 创建临时文件夹
temp_dir = os.path.join(os.getcwd(), "temp")
os.makedirs(temp_dir, exist_ok=True)
# 创建一个简单的LaTeX模板文件
latex_template = r"""
\documentclass{article}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{unicode-math}
\begin{document}
$body$$
\end{document}
"""
template_path = os.path.join(temp_dir, "latex_template.tex")
with open(template_path, "w") as f:
    f.write(latex_template)


@app.post("/convert/")
async def convert_markdown_to_docx(input_file: UploadFile = File(...),
                                   output_file: str = "output.docx"):
    temp_markdown_fd, temp_markdown_path = tempfile.mkstemp(
        suffix=".md", dir=temp_dir)
    os.close(temp_markdown_fd)

    with open(temp_markdown_path, "wb") as buffer:
        buffer.write(await input_file.read())

    docx_path = os.path.join(temp_dir, output_file)
    try:
        result = subprocess.run([
            "pandoc",
            temp_markdown_path,
            "-o", docx_path,
            "--from=markdown+tex_math_dollars+tex_math_single_backslash+latex_macros",
            "--to=docx",
            "--mathjax",
            "--standalone",
            "--wrap=none",
            "--filter=pandoc-crossref",
            "--citeproc",
            "--pdf-engine=xelatex",
            "-V", "mainfont:DejaVu Sans",
            "-V", "mathfont:DejaVu Math TeX Gyre"
        ], check=True, capture_output=True, text=True)
        logger.info(f"Conversion successful. Output: {result.stdout}")
    except subprocess.CalledProcessError as e:
        logger.error(f"Conversion failed. Error: {e.stderr}")
        raise HTTPException(
            status_code=500, detail=f"Conversion failed: {e.stderr}")

    os.remove(temp_markdown_path)

    return FileResponse(docx_path, media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document', filename=output_file)


@app.get("/status/")
def status_check():
    return {"status": "Service is running"}


@app.on_event("shutdown")
def cleanup():
    # 删除服务运行期间创建的所有临时文件
    for filename in os.listdir(temp_dir):
        file_path = os.path.join(temp_dir, filename)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception as e:
            logger.error(f"Error deleting {file_path}: {e}")
